package com.woniuxy.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniuxy.conmon.MyPageData;
import com.woniuxy.pojo.Hospital;
import com.woniuxy.pojo.Result;
import com.woniuxy.pojo.dto.BatchStatusDTO;
import com.woniuxy.pojo.dto.DepartmentDTO;
import com.woniuxy.pojo.dto.HospitalDTO;
import com.woniuxy.pojo.dto.HospitalStatusDTO;
import com.woniuxy.pojo.vo.HospitalDetailVO;
import com.woniuxy.service.HospitalService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("hospital")
@Api(tags = "医院管理接口")
@Slf4j
public class HospitalController {
    @Autowired
    private HospitalService hospitalService;
    @GetMapping("/getHospital/{pageNum}/{pageSize}")
    @ApiOperation(value = "获取医院信息")
    public ResponseEntity<MyPageData> getHospital(@PathVariable("pageNum") Integer pageNum, @PathVariable("pageSize") Integer pageSize) {
        //加分页效果
        Page<Hospital> page = hospitalService.page(new Page<>(pageNum, pageSize));
        MyPageData myPageData = new MyPageData(page.getTotal(), page.getRecords());
        log.info("获取医院信息成功");
        return ResponseEntity.ok(myPageData);
    }
    @GetMapping("/getHospitalType")
    @ApiOperation(value = "获取医院的类型")
    public Result getHospitalType() {
        QueryWrapper<Hospital> queryWrapper = new QueryWrapper<>();
        //去重
        queryWrapper.select("type").groupBy("type");
        List<String> types = new ArrayList<>();
        hospitalService.listMaps(queryWrapper).forEach(map -> {
            types.add(map.get("type").toString());
        });
        log.info("获取医院的类型成功");
        return Result.ok(types);
    }
    @GetMapping("/getHospitalLevel")
    @ApiOperation(value = "获取医院的等级")
    public Result getHospitalLevel() {
        QueryWrapper<Hospital> queryWrapper = new QueryWrapper<>();
        //去重
        queryWrapper.select("level").groupBy("level");
        List<String> levels = new ArrayList<>();
        hospitalService.listMaps(queryWrapper).forEach(map -> {
            levels.add(map.get("level").toString());
        });
        log.info("获取医院的等级成功");
        return Result.ok(levels);
    }
    @PostMapping("/searchHospital/{pageNum}/{pageSize}")
    @ApiOperation(value = "搜索医院")
    public ResponseEntity<MyPageData> searchHospital(
            @RequestBody HospitalDTO queryDTO,  // 使用专用DTO
            @PathVariable("pageNum") Integer pageNum,
            @PathVariable("pageSize") Integer pageSize) {

        LambdaQueryWrapper<Hospital> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(queryDTO.getName()), Hospital::getName, queryDTO.getName());
        queryWrapper.eq(StringUtils.isNotBlank((CharSequence) queryDTO.getType()), Hospital::getType, queryDTO.getType());
        queryWrapper.eq(StringUtils.isNotBlank(queryDTO.getLevel()), Hospital::getLevel, queryDTO.getLevel());
        Page<Hospital> page = hospitalService.page(new Page<>(pageNum, pageSize), queryWrapper);
        return ResponseEntity.ok(new MyPageData(page.getTotal(), page.getRecords()));
    }
    @PostMapping("/batchDeleteHospital")
    @ApiOperation(value = "批量删除医院")
    public Result batchDeleteHospital(@RequestBody List<Integer> ids) {
        boolean b = hospitalService.removeByIds(ids);
        if (b) {
            log.info("批量删除医院成功");
            return Result.ok("批量删除医院成功");
        } else {
            log.info("批量删除医院失败");
            return Result.fail("批量删除医院失败");
        }

    }
    @PostMapping("/updateStatus")
    @ApiOperation("更新医院状态")
    public Result updateStatus(@RequestBody HospitalStatusDTO dto) {
        Hospital hospital = hospitalService.getById(dto.getId());
        if (hospital == null) {
            return Result.fail("医院不存在");
        }
        hospital.setStatus(dto.getStatus());
        boolean success = hospitalService.updateById(hospital);
        return success ? Result.ok() : Result.fail("状态更新失败");
    }
    @PostMapping("/batchUpdateStatus")
    @ApiOperation("批量更新医院状态")
    public Result batchUpdateStatus(@RequestBody BatchStatusDTO dto) {
        if (dto.getIds() == null || dto.getIds().isEmpty()) {
            return Result.fail("请选择要操作的医院");
        }
        boolean success = hospitalService.lambdaUpdate()
                .in(Hospital::getId, dto.getIds())
                .set(Hospital::getStatus, dto.getStatus())
                .update();
        return success ? Result.ok() : Result.fail("批量操作失败");
    }
    @GetMapping("/getHospitalDetail/{id}")
    @ApiOperation("获取医院详情")
    public Result<HospitalDetailVO> getHospitalDetail(@PathVariable int id) {
        Hospital hospital = hospitalService.getById(id);
        if (hospital == null) {
            return Result.fail("医院不存在");
        }

        // 转换为VO对象
        HospitalDetailVO vo = new HospitalDetailVO();
        BeanUtils.copyProperties(hospital, vo);

        // 处理科室信息
        if (StringUtils.isNotBlank(hospital.getDepartments())) {
            vo.setDepartments(JSON.parseArray(hospital.getDepartments(), DepartmentDTO.class));
        }
        // 处理服务标签
        if (StringUtils.isNotBlank(hospital.getServiceTags())) {
            vo.setServiceTags(Arrays.asList(hospital.getServiceTags().split(",")));
        }
        return Result.ok(vo);
    }

}
